package org.zhuxian.cn.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zhuxian.cn.entity.EquipmentBuilds;
import org.zhuxian.cn.entity.EquipmentBuildsLike;
import org.zhuxian.cn.mapper.EquipmentBuildsLikeMapper;
import org.zhuxian.cn.mapper.EquipmentBuildsMapper;
import org.zhuxian.cn.service.EquipmentBuildsLikeService;


@Service
public class EquipmentBuildsLikeServiceImpl extends ServiceImpl<EquipmentBuildsLikeMapper, EquipmentBuildsLike> implements EquipmentBuildsLikeService {

    @Autowired
    private EquipmentBuildsLikeMapper equipmentBuildsLikeMapper;

    @Autowired
    private EquipmentBuildsMapper equipmentBuildsMapper;

    @Override
    @Transactional
    public boolean like(Integer buildId, Long userId) {
        // 检查是否已经点赞
        if (hasLiked(buildId, userId)) {
            return false;
        }

        // 创建点赞记录
        EquipmentBuildsLike like = new EquipmentBuildsLike();
        like.setBuildId(buildId);
        like.setUserId(userId);
        boolean success = save(like);

        if (success) {
            // 更新配装表中的点赞统计
            EquipmentBuilds build = equipmentBuildsMapper.selectById(buildId);
            if (build != null) {
                build.setLikeCountStatistics(build.getLikeCountStatistics() + 1);
                equipmentBuildsMapper.updateById(build);
            }
        }

        return success;
    }

    @Override
    @Transactional
    public boolean unlike(Integer buildId, Long userId) {
        // 查找点赞记录
        EquipmentBuildsLike like = equipmentBuildsLikeMapper.findByBuildIdAndUserId(buildId, userId);
        if (like == null) {
            return false;
        }

        // 删除点赞记录
        boolean success = removeById(like.getId());

        if (success) {
            // 更新配装表中的点赞统计
            EquipmentBuilds build = equipmentBuildsMapper.selectById(buildId);
            if (build != null && build.getLikeCountStatistics() > 0) {
                build.setLikeCountStatistics(build.getLikeCountStatistics() - 1);
                equipmentBuildsMapper.updateById(build);
            }
        }

        return success;
    }

    @Override
    public boolean hasLiked(Integer buildId, Long userId) {
        return equipmentBuildsLikeMapper.findByBuildIdAndUserId(buildId, userId) != null;
    }

    @Override
    public Integer getLikeCount(Integer buildId) {
        return equipmentBuildsLikeMapper.countByBuildId(buildId);
    }
}